package Semaphore_8;
import java.util.concurrent.Semaphore;
public class 公平模式_按请求顺序分配许可 {
    public static void main(String[] args) {
        final int THREAD_COUNT = 10;
        // 使用公平模式(true参数)
        final Semaphore semaphore = new Semaphore(1, true);

        for (int i = 0; i < THREAD_COUNT; i++) {
            final int threadId = i;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        System.out.println("线程-" + threadId + " 请求许可");
                        semaphore.acquire();

                        System.out.println("线程-" + threadId + " 获得许可");
                        Thread.sleep(300); // 模拟工作

                        semaphore.release();
                        System.out.println("线程-" + threadId + " 释放许可");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

            // 延迟启动线程，更好观察公平性
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}